package com._CPA_.controller;

import com._CPA_.dao.UserMapper;
import com._CPA_.pojo.Result;
import com._CPA_.pojo.UserInfo;
import com._CPA_.service.UserService;
import com._CPA_.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping(value = "/user")
@Api(tags = "用户模块")
public class UserController {
    @Autowired //请求对象
    HttpServletRequest httpServletRequest;
    @Autowired
    private UserService userService;


    @Autowired
    private UserMapper userMapper;

    public static Logger getLog() {
        return log;
    }

    /**
     *  用户登录
     * @param
     * @param
     * @param
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录",notes = "该接口用于用户登录智慧编程,包括用户名和手机号登录，登录完毕后，系统下发 JWT令牌。")
    public Result login(@RequestBody UserInfo user)
    {
        if (user.getUserName()!=null){
        log.info("user用户名登录: {}", user);
        UserInfo u =userService.loginByName(user);
        //登录成功,生成令牌,下发令牌
            if (u != null){
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", u.getUserId());
                claims.put("name", u.getUserName());
                claims.put("username", u.getPhone());
                String jwt = JwtUtils.generateJwt(claims); //jwt包含了当前登录的员工信息
                return Result.success(jwt);
            }
            //登录失败, 返回错误信息
            return Result.error("用户名或密码错误");
        }
        else{
            log.info("user手机号登录: {}", user);
            UserInfo u =userService.loginByPhone(user);
            //登录成功,生成令牌,下发令牌
            if (u != null){
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", u.getUserId());
                claims.put("name", u.getUserName());
                claims.put("phone", u.getPhone());
                String jwt = JwtUtils.generateJwt(claims); //jwt包含了当前登录的员工信息
                return Result.success(jwt);
            }
            //登录失败, 返回错误信息
            return Result.error("手机号或密码错误");
        }
    }


    /**
     * 用户注册方法
     * @param user
     * @return
     */
    @PostMapping("/reg")
    @ApiOperation(value = "用户注册",notes = "用于用户注册信息")
    public Result register(@RequestBody @ApiParam(name = "user",value = "用户实体类",required = true) UserInfo user){
           log.info("user注册: {}", user);
           //注册判断和生成相应信息
           if (userService.isOnlyPhone(user.getPhone() ) == false){
               return Result.error("手机号重复，请重新输入");
           }
           else if (userService.isOnlyName(user.getUserName())==false){
                   return Result.error("用户名重复，请重新输入");
               }
           else {
                  userService.register(user);
                  return Result.success("注册成功");

               }

           }


    /**
     * 用户注销方法
     */
    @DeleteMapping ("/del")
    @ApiOperation(value = "用户注销",notes = "用于用户注销账户")
    public Result cancellation(@RequestBody UserInfo user){
        log.info("user注销: {}", user);
        if (user.getUserName() != null){
            userService.isOnlyDelete(user.getUserName());
            return Result.success("注销成功");
        }
        return Result.error("注销失败,用户名为空");
    }


    /**
     *  用户修改信息
     */
    @PutMapping("/modify")
    @ApiOperation(value = "修改信息",notes = "用于用户修改自身信息")
    public Result changeInformation(@RequestBody UserInfo user){
        log.info("user修改信息: {}", user);
        if (userService.isOnlyPhone(user.getPhone() ) == false){
            return Result.error("手机号重复，请重新输入");
        }
        else {
            userService.isOnlyUpdate(user);
            return Result.success("修改成功");

        }
    }


    /**
     * 用来接收用户修改密码请求，对旧密码进行判断
     * @param user
     * @return
     */
    @GetMapping("/pwd")
    @ApiOperation(value = "密码判断",notes = "用来接收用户修改密码请求，对旧密码进行判断")
    public Result getPassWord(@RequestBody UserInfo user){
        log.info("user旧密码验证: {}", user);
        if (user != null){
            if (userService.isOnlyGetPassWord(user.getPassword(), user.getUserId()) == false){
                return Result.error("旧密码重复");
            }
            else {
                return Result.success("密码验证通过");
            }
        }
        return Result.error("验证失败");
    }


    /**
     * 用来接收用户修改密码请求，对旧密码进行修改
     * @param user
     * @return
     */
    @PutMapping ("/pwd")
    @ApiOperation(value = "用户修改密码",notes = "用来接收用户修改密码请求，对旧密码进行修改")
    public Result putPassWord(@RequestBody UserInfo user){
        log.info("user新密码修改: {}", user);
        if (user != null){
            userService.isOnlyPutPassWord(user);
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }


    @GetMapping("/info")
    public Result selectAll(){


        //获取 操作用户ID
        String jwt = httpServletRequest.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        //解析map结合
        String id = (String) claims.get("id");
        log.info("返回用户的所有信息");
        UserInfo u = userService.selectUserAll(id);
        return Result.success(u);
    }

}
